package cn.iocoder.an.module.business.service.storemanage;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.an.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.an.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.an.module.business.controller.admin.equipmentmanage.vo.ImportRespVO;
import cn.iocoder.an.module.business.dal.dataobject.drawconfig.DrawConfigDO;
import cn.iocoder.an.module.business.dal.dataobject.storeinit.StoreInitDO;
import cn.iocoder.an.module.business.dal.mysql.storeinit.StoreInitMapper;
import cn.iocoder.an.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.an.module.system.dal.mysql.user.AdminUserMapper;
import cn.iocoder.an.module.system.service.permission.PermissionService;
import cn.iocoder.an.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.micrometer.common.util.StringUtils;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import cn.iocoder.an.module.business.controller.admin.storemanage.vo.*;
import cn.iocoder.an.module.business.dal.dataobject.storemanage.StoreManageDO;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.pojo.PageParam;
import cn.iocoder.an.framework.common.util.object.BeanUtils;

import cn.iocoder.an.module.business.dal.mysql.storemanage.StoreManageMapper;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.an.module.business.enums.ErrorCodeConstants.*;

/**
 * 出入库管理 Service 实现类
 *
 * @author zzy
 */
@Service
@Validated
public class StoreManageServiceImpl implements StoreManageService {

    @Resource
    private StoreManageMapper storeManageMapper;


    @Resource
    private AdminUserService adminUserService;

    @Resource
    private StoreInitMapper storeInitMapper;

    @Resource
    private PermissionService permissionService;


    @Override
    public Long createStoreManage(StoreManageSaveReqVO createReqVO) {
        // 插入
        StoreManageDO storeManage = BeanUtils.toBean(createReqVO, StoreManageDO.class);

        //查询对应的期初台账有没有 没有就提示
        //查询期初数量
        LambdaQueryWrapper<StoreInitDO> initWrapper = new LambdaQueryWrapper<>();
        initWrapper.eq(StoreInitDO::getCustomerAccount, createReqVO.getCustomerAccount());
        initWrapper.eq(StoreInitDO::getDrawingNumber, createReqVO.getDrawingNumber());
        try {
            storeInitMapper.selectList(initWrapper).getFirst();
        } catch (Exception e) {
            throw exception("请先添加期初库存台账数据");
        }
        storeManageMapper.insert(storeManage);
        // 返回
        return storeManage.getId();
    }

    @Override
    public void updateStoreManage(StoreManageSaveReqVO updateReqVO) {
        // 校验存在
        validateStoreManageExists(updateReqVO.getId());
        // 更新
        StoreManageDO updateObj = BeanUtils.toBean(updateReqVO, StoreManageDO.class);
        storeManageMapper.updateById(updateObj);
    }

    @Override
    public void deleteStoreManage(Long id) {
        // 校验存在
        validateStoreManageExists(id);
        // 删除
        storeManageMapper.deleteById(id);
    }

    @Override
    public void deleteStoreManageListByIds(List<Long> ids) {
        // 删除
        storeManageMapper.deleteByIds(ids);
    }


    private void validateStoreManageExists(Long id) {
        if (storeManageMapper.selectById(id) == null) {
            throw exception(STORE_MANAGE_NOT_EXISTS);
        }
    }

    @Override
    public StoreManageDO getStoreManage(Long id) {
        return storeManageMapper.selectById(id);
    }

    @Override
    public PageResult<StoreManageDO> getStoreManagePage(StoreManagePageReqVO pageReqVO) {
        //查询自己的
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserDO user = adminUserService.getUser(loginUserId);
        //

        if (permissionService.hasAnyRoles(SecurityFrameworkUtils.getLoginUserId(), "super_admin", "tenant_admin")) {//判断是不是管理员
            //查询全部
            if (StringUtils.isNotEmpty(pageReqVO.getCustomerAccount())) {
                pageReqVO.setCustomerAccount(pageReqVO.getCustomerAccount());
            } else {
                pageReqVO.setCustomerAccount(null);
            }
        } else {
            if (user != null) {
                pageReqVO.setCustomerAccount(user.getUsername());
            }

        }

        PageResult<StoreManageDO> pageResult = storeManageMapper.selectPage(pageReqVO);
        pageResult.getList().forEach(storeManageDO -> {
            //查询期初数量
            LambdaQueryWrapperX<StoreInitDO> initWrapper = new LambdaQueryWrapperX<>();
            initWrapper.eqIfPresent(StoreInitDO::getCustomerAccount, storeManageDO.getCustomerAccount());
            initWrapper.eq(StoreInitDO::getDrawingNumber, storeManageDO.getDrawingNumber());
            List<StoreInitDO> storeInitDOS = storeInitMapper.selectList(initWrapper);
            StoreInitDO storeInitDO = null;
            Integer initAmount = 0;
            if (storeInitDOS != null && storeInitDOS.size() > 0) {
                storeInitDO = storeInitDOS.getFirst();
                initAmount = storeInitDO.getInitAmount();
            }

            StoreManagePageReqVO reqVO = new StoreManagePageReqVO();
            reqVO.setCustomerAccount(storeManageDO.getCustomerAccount());
            reqVO.setDrawingNumber(storeManageDO.getDrawingNumber());
            reqVO.setOperDate(storeManageDO.getOperDate());
            //查询历史出入库

            Long inCountLong = storeManageMapper.selectInCount(reqVO);
            Integer inCount = (inCountLong == null) ? 0 : inCountLong.intValue();

            Long outCountLong = storeManageMapper.selectOutCount(reqVO);
            Integer outCount = (outCountLong == null) ? 0 : outCountLong.intValue();

            Integer currentAmount = initAmount + inCount - outCount;
            storeManageDO.setCurrentAmount(currentAmount);

            storeManageDO.setInitAmount(initAmount);

        });
        return pageResult;
    }

    @Override
    public ImportRespVO importList(List<StoreManageImportVo> list, boolean isUpdateSupport) {
        // 1.1 参数校验
        if (CollUtil.isEmpty(list)) {
            throw exception(IMPORT_EQUIPMENT_MANAGE_NOT_EXISTS);
        }

        //2.记录成功或失败记录
        ImportRespVO respVO = ImportRespVO.builder().insertNameList(new ArrayList<>())
                .updateNameList(new ArrayList<>()).failureMap(new LinkedHashMap<>()).build();

        AtomicInteger count = new AtomicInteger(1);
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserDO user = adminUserService.getUser(loginUserId);
        String userName = user.getUsername();
        //
        List<StoreManageDO> rusultList = new ArrayList<>();

        list.forEach(drawConfig -> {
            count.incrementAndGet();//记录行号

            if (drawConfig.getOperDate() == null) {
                throw exception("第" + count + "行数据" + "日期不能为空");
            }

            // 2. 不能是未来日期（根据业务需求）
            LocalDate today = LocalDate.now();
            if (drawConfig.getOperDate().isAfter(today)) {
                throw exception("第" + count + "行数据：操作日期不能晚于今天");
            }

            if (StringUtils.isEmpty(drawConfig.getDrawingNumber())) {
                throw exception("第" + count + "行数据：图号不能为空");
            }

            if (!userName.equals(drawConfig.getCustomerAccount())) {
                throw exception("第" + count + "行数据：客户账号与登录账号不匹配");
            }

            //
            LambdaQueryWrapper<StoreInitDO> queryWrapper = new LambdaQueryWrapper<StoreInitDO>();
            queryWrapper.eq(StoreInitDO::getCustomerAccount, userName);
            queryWrapper.eq(StoreInitDO::getDrawingNumber, drawConfig.getDrawingNumber());
            boolean exists = storeInitMapper.exists(queryWrapper);
            if (!exists) {
                throw exception("第" + count + "行数据" + "图号:" + drawConfig.getDrawingNumber() + "在期初库存台账中不存在!");
            }
            rusultList.add(BeanUtils.toBean(drawConfig, StoreManageDO.class));
            respVO.getInsertNameList().add(drawConfig.getDrawingNumber());
        });
        if (respVO.getFailureMap().size() > 0) {
            respVO.getInsertNameList().clear();
            return respVO;
        }
        //一次性保存
        storeManageMapper.insertBatch(rusultList);

        return respVO;
    }

}